using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using MESData.ErrorCode;
using MESData.ProductionPlan.API.DTO;
using MESData.ProductionPlan.API.Services;
using MESData.ProductionPlan.API.Extensions;

namespace MESData.ProductionPlan.API.Controllers
{
    /// <summary>
    /// 项目控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize] // 添加认证要求
    public class ProjectController : ControllerBase
    {
        private readonly IProjectService _projectService;

        public ProjectController(IProjectService projectService)
        {
            _projectService = projectService;
        }

        /// <summary>
        /// 获取所有项目（用于下拉框选择）
        /// </summary>
        [HttpGet("all")]
        [AllowAnonymous] // 下拉框接口允许匿名访问
        public async Task<ApiResult<List<ProjectSelectDto>>> GetAllProjects([FromQuery] ProjectQueryDto? queryDto = null)
        {
            return await _projectService.GetAllProjectsAsync(queryDto);
        }

        /// <summary>
        /// 分页查询项目
        /// </summary>
        [HttpPost("page")]
        [AllowAnonymous] // 查询接口允许匿名访问
        public async Task<ApiResult<List<ProjectDto>>> GetProjectsPage([FromBody] ProjectQueryDto queryDto)
        {
            return await _projectService.GetProjectsPageAsync(queryDto);
        }

        /// <summary>
        /// 根据ID获取项目详情
        /// </summary>
        [HttpGet("{id}")]
        [AllowAnonymous] // 详情接口允许匿名访问
        public async Task<ApiResult<ProjectDto>> GetProjectById(int id)
        {
            return await _projectService.GetProjectByIdAsync(id);
        }

        /// <summary>
        /// 新增项目
        /// </summary>
        [HttpPost("create")]
        public async Task<ApiResult<bool>> CreateProject([FromBody] ProjectDto dto)
        {
            var operatorName = User.GetUserAccount();
            return await _projectService.CreateProjectAsync(dto, operatorName);
        }

        /// <summary>
        /// 更新项目
        /// </summary>
        [HttpPut("{id}")]
        public async Task<ApiResult<bool>> UpdateProject(int id, [FromBody] ProjectDto dto)
        {
            var operatorName = User.GetUserAccount();
            return await _projectService.UpdateProjectAsync(id, dto, operatorName);
        }

        /// <summary>
        /// 删除项目
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<ApiResult<bool>> DeleteProject(int id)
        {
            var operatorName = User.GetUserAccount();
            return await _projectService.DeleteProjectAsync(id, operatorName);
        }
    }
} 